package com.antdesignbackend.backend.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.antdesignbackend.backend.common.http.HttpClientResult;
import com.antdesignbackend.backend.common.http.HttpClientUtils;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.entity.Shop;
import com.antdesignbackend.backend.service.IShopService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.List;

/**
 * Created by Administrator on 2020/6/8.
 */
@Controller
@RequestMapping("/wechat")
public class WechatController {
    private String appid=WebConfig.APPID;

    private String secret=WebConfig.AppSecret;
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    IShopService shopService;
    /**
     * 微信登录
     *
     * @param code
     * @param redirectUrl 返回用户的登录地址
     * @param request
     * @param response
     * @param model
     * @return
     * @throws
     */
    @RequestMapping(value = "/weixinLogin")
    public String weixinLogin(String code, String redirectUrl, HttpServletRequest request,
                              HttpServletResponse response, ModelMap model) throws IOException {
        String redirect_uri = WebConfig.redirect_uri;

//-----在这里判断code是否已经存在于缓存中，如果存在，说明code已经使用过，需要重新获取code------
        List list = (List) request.getSession().getAttribute("openid_list");
        if (StringUtils.isNotBlank(code) && list != null && list.contains(code)) {
            //用过了
            code = "";
        }
        //获取code
        if (StringUtils.isBlank(code)) {
            try {
                PrintWriter out = response.getWriter();
                out.println("<script>window.location.href='" + getCodeUrl(redirect_uri) + "'</script>");
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }
        String[] s = getOpenId(code);
        String openId = s[0];
        String accessToken = s[1];
        System.out.println("手机登录openId=================================>" + openId);
        log.info("手机登录openId=================================>" + openId);
        //通过openId查询所对应的商户
//        String openId = "olfy2wB0RHDZM8-8IatZC1-ufhe4";
        try {
            QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("OpenId",openId);
            List<Shop> shops = shopService.list(queryWrapper);
            //将商铺集合返回给页面
            model.addAttribute("shops",shops);
        }catch (Exception e){
            log.error(e.getMessage());
        }
        //将openId发给页面
        model.addAttribute("openId",openId);
        return "wx/index";
    }

    /**
     * 获取用户授权 得到openId,accessToken
     *
     * @param code
     * @return
     */
    public String[] getOpenId(String code) {
        String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?grant_type=authorization_code";
        tokenUrl = tokenUrl + "&appid=" + appid + "&secret=" + secret + "&code=" + code;
        JSONObject json = null;
        try {
            HttpClientResult httpClientResult= HttpClientUtils.doGet(tokenUrl);
            String content=httpClientResult.getContent();
            json= JSONArray.parseObject(content);
            //------------在这里把使用过的code存入到缓存中--------

        } catch (JSONException e2) {
            e2.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String openId = "";
        String accessToken = "";
        String[] s = new String[2];
        if (json != null) {
            try {
                openId = json.getString("openid");
                accessToken = json.getString("access_token");
                s[0] = openId;
                s[1] = accessToken;
            } catch (JSONException e) {
                String errcode = null;
                try {
                    errcode = json.getString("errcode");
                    System.out.println("errcode================>手机登录 获取用户授权失败" + errcode);
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return s;
    }
    /**
     * 获取code请求地址
     *
     * @param redirect_uri  回调地址  这个回调地址需要在微信公众号后台也进行配置 不然会显示"redirect_uri域名还是与后台配置不一致"
     * @param
     * @return
     */
    public String getCodeUrl(String redirect_uri) {
        redirect_uri= URLEncoder.encode(redirect_uri);   //使用 urlEncode 对链接进行处理
        String codeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize";
        codeUrl = codeUrl + "?appid=" + appid + "&redirect_uri=" + redirect_uri
                + "&response_type=code&scope=snsapi_userinfo&state=jetcms#wechat_redirect";

        return codeUrl;
    }

    /**
     * 绑定用户微信id
     * @return
     */
    @PostMapping(value = "/binding")
    @ResponseBody
    public ReturnVO binding(@RequestBody Shop shop){
        ReturnVO returnVO = new ReturnVO();
        try {
            //查询用户输入的用户名和手机号是否正确
            QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
            if (shop.getPerson() != null && !shop.getPerson().equals(""))
                queryWrapper.eq("Person",shop.getPerson());
            if (shop.getPhone() != null && !shop.getPhone().equals(""))
                queryWrapper.eq("Phone",shop.getPhone());
            List<Shop> list = shopService.list(queryWrapper);
            if (list.size() > 0){
                UpdateWrapper<Shop> updateWrapper = new UpdateWrapper<>();
                if (shop.getOpenId() != null && !shop.getOpenId().equals("")){
                    updateWrapper.set("OpenId",shop.getOpenId())
                                .eq("Person",shop.getPerson())
                                .eq("Phone",shop.getPhone());
                    shopService.update(updateWrapper);
                    returnVO.setCode("200");
                }
            }else {
                returnVO.setCode("400");
                returnVO.setMessage("没找到该商户");
            }
        }catch (Exception e){
            returnVO.setCode("500");
            returnVO.setMessage(e.getMessage());
            log.error(e.getMessage());
        }
        return returnVO;
    }


}
